﻿using System;
using System.Net;
using Wx.Standard.Base;
using Wx.Standard.Common;
using Wx.Standard.Extend;
using Wx.Standard.IService;
using Wx.Standard.Model;
using Wx.Standard.Model.Self;
using Wx.Standard.Model.Share;

namespace Wx.Standard.Service
{
    public class Web : IWeb
    {
        WxApi wxApi;
        internal Web(WxApi wxApi)
        {
            this.wxApi = wxApi;
        }
        private Web() { }
        void IWeb.Auth(string url, string stata, bool agree)
        {
            if (!string.IsNullOrWhiteSpace(stata))
            {
                stata = WebUtility.UrlEncode(StringEncyptionHelper.aesEncrypt(stata));
            }
            var link = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={wxApi.apiOption.appid}&redirect_uri={url}&response_type=code&scope=snsapi_userinfo&state={stata}#wechat_redirect";
            if (!agree)
            {
                link = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={wxApi.apiOption.appid}&redirect_uri={url}&response_type=code&scope=snsapi_base&state={stata}#wechat_redirect";
            }
            wxApi.context.Response.Redirect(link);
        }

        byte[] IWeb.GetImg(string url)
        {
            var bts = HttpHelper.getBytes<string>(url);
            return bts;
        }

        JsShare IWeb.GetJsShareConfig(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new WeChatError("Url值为空");
            }
            var jsapi_ticket = BaseClass.getJsApi_Ticket(wxApi.apiOption);
            var timestamp = StringHelper.convertDateTimeInt(DateTime.Now);
            var noncestr = StringHelper.getRandomString(16);
            var signature = StringEncyptionHelper.sha1(string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", jsapi_ticket, noncestr, timestamp, url)).ToLower();
            var jsapi = new JsShare()
            {
                appId = wxApi.apiOption.appid,
                nonceStr = noncestr,
                signature = signature,
                timestamp = timestamp
            };
            return jsapi;
        }

        string IWeb.GetQRcodeImgSrc(int scene_id, int expire_seconds)
        {
            var access_token = BaseClass.getAccessToken(wxApi.apiOption);
            var url = $"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={access_token}";
            var postData = string.Empty;

            if (expire_seconds == 0)
            {
                postData = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}";
            }
            else
            {
                postData = "{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}";
            }
            postData = postData.Replace("123", scene_id.ToString()).Replace("604800", expire_seconds.ToString());
            string str = BaseClass.postFormWechatService(postData, url);
            QRcodeTicket qt = JsonHelper.jsonToModel<QRcodeTicket>(str);
            var realurl = $"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={qt.ticket}";
            return realurl;
        }
        string IWeb.GetQRcodeImgSrc(string scene_str, int expire_seconds)
        {
            var access_token = BaseClass.getAccessToken(wxApi.apiOption);
            var url = $"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={access_token}";
            var postData = string.Empty;

            if (expire_seconds == 0)
            {
                postData = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"123\"}}}";
            }
            else
            {
                postData = "{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"123\"}}}";
            }
            postData = postData.Replace("123", scene_str).Replace("604800", expire_seconds.ToString());
            string str = BaseClass.postFormWechatService(postData, url);
            QRcodeTicket qt = JsonHelper.jsonToModel<QRcodeTicket>(str);
            var realurl = $"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={qt.ticket}";
            return realurl;
        }

        string IWeb.GetOpenidWithAuth(string code)
        {
            try
            {
                if (string.IsNullOrEmpty(code))
                {
                    return null;
                }
                var url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={wxApi.apiOption.appid}&secret={wxApi.apiOption.appsecret}&code={code}&grant_type=authorization_code";
                //获取authAccesstoken
                var str = BaseClass.getFormWechatService(url);
                var authAccesstoken = JsonHelper.jsonToModel<AuthAccessToken>(str);
                if (authAccesstoken != null)
                {
                    return authAccesstoken.openid;
                }

            }
            catch (Exception ex)
            {
                throw new WeChatError($"{this.GetType().Name}:{ex.Message}");
            }
            return null;
        }

        WeChatUser IWeb.GetUserWithAuth(string code)
        {
            try
            {
                if (string.IsNullOrEmpty(code))
                {
                    return null;
                }
                var url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={wxApi.apiOption.appid}&secret={wxApi.apiOption.appsecret}&code={code}&grant_type=authorization_code";
                //获取authAccesstoken
                var str = BaseClass.getFormWechatService(url);
                var authAccesstoken = JsonHelper.jsonToModel<AuthAccessToken>(str);
                if (authAccesstoken != null)
                {
                    //获取用户信息
                    var urlforuser = $"https://api.weixin.qq.com/sns/userinfo?access_token={authAccesstoken.access_token}&openid={authAccesstoken.openid}&lang=zh_CN";
                    var user = JsonHelper.jsonToModel<WeChatUser>(BaseClass.getFormWechatService(urlforuser));
                    return user;
                }

            }
            catch (Exception ex)
            {
                throw new WeChatError($"{this.GetType().Name}:{ex.Message}");
            }
            return null;
        }
    }
}
